package com.aquarium.ui;

import java.util.Observable;
import java.util.Observer;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.aquarium.R;
import com.aquarium.alarm.AlarmManager;
import com.aquarium.bt.BTManager;
import com.aquarium.bt.DataInterpreter;
import com.aquarium.bt.DataStruct;
import com.aquarium.config.AlarmDefaultValue;
import com.aquarium.config.BTCommand;
import com.aquarium.mail.MailInfo;
import com.aquarium.util.ConfigDOM;

public class AlarmSettingActivity extends Activity implements OnClickListener,
		Observer {
	// AlarmValue alarmValue;
	AlarmManager mAlarmManager;
	String hour;
	String minute;

	private float mPhMin;
	private float mSettingPhMin = 1f;
	private float mPhMax;
	private float mSettingPhMax = 14f;
	private float mTemperatureMin;
	private float mSettingTemperatureMin = 0f;
	private float mTemperatureMax;
	private float mSettingTemperatureMax = 100f;
	private float mOxygenMin;
	private float mSettingOxygenMin = 0f;
	private float mOxygenMax;
	private float mSettingOxygenMax = 1000f;
	private float mConductivityMin;
	private float mSettingConductivityMin = 1.0f;
	private float mConductivityMax;
	private float mSettingConductivityMax = 1.1f;
	private float mWaterLevelMax;
	private float mSettingWaterLevelMax = 1000f;
	private float mWaterLevelMin;
	private float mSettingWaterLevelMin = 0f;
	private int mPhAlarmInterval;
	private int mTemperatureAlarmInterval;
	private int mOxygenAlarmInterval;
	private int mConductivityAlarmInterval;
	private int mWaterLevelAlarmInterval;
	private String mPhoneNum;
	private String mEmialAddr;
	private boolean mPhoneEnable;
	private boolean mEmailEnable;
	private boolean mRangEnable;
	private BTManager mBtManager;
	String TAG = "AlarmSettingActivity";
	public static final int ButtonRingtone = 2;
	private MailInfo mailInfo;
	MyHandler myHandler;
	float mincondutivity;
	float maxcondutivity;
	float minoxygen;
	float maxoxygen;
	float minph;
	float maxph;
	float mintemperature;
	float maxtemperature;
	float minwaterlevel;
	float maxwaterlevel;

	final static int HANDLER_VIEW_ENABLE = 0;
	final static int HANDLER_TIMEOUT = 1;
	final static int HANDLER_VERIFY_OK = 2;
	final static int HANDLER_VERIFY_ERR = 3;
	final static int HANDLER_SAVE_CONDUTIVITY = 4;
	final static int HANDLER_SAVE_OXYGEN = 5;
	final static int HANDLER_SAVE_PH = 6;
	final static int HANDLER_SAVE_TEMPERATURE = 7;
	final static int HANDLER_SAVE_WATERLEVEL = 8;
	final static int HANDLER_VIEW_DISENABLE = 9;

	final static int TIMEOUT = 10 * 1000;

	Context mContext;
	final static int FLAG_PH = 1 << 5;
	final static int FLAG_WATERLEVEL = 1 << 4;
	final static int FLAG_TEMPERATURE = 1 << 3;
	final static int FLAG_CONDUCTIVITY = 1 << 2;
	final static int FLAG_OXYGEN = 1;
	static int sendFlag = 0;
	static int receiveFlag = 0;
	private DataInterpreter mDataInterpreter;
	ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mContext = this;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarmsetting);
		myHandler = new MyHandler();
		mDataInterpreter = new DataInterpreter();
		mAlarmManager = AlarmManager.getInstance(this);
		mAlarmManager.addObserver(this);
		mailInfo = MailInfo.getInstance(this);
		hour = getResources().getString(R.string.hour);
		minute = getResources().getString(R.string.minute);
		mBtManager = BTManager.getInstance();
		mBtManager.init(getApplicationContext());
		mBtManager.addObserver(this);
		initValue();
		initAllView();
		setOnListener();
	}

	private void initValue() {
		mPhMin = mAlarmManager.getPhMin();
		mPhMax = mAlarmManager.getPhMax();
		mPhAlarmInterval = mAlarmManager.getPhAlarmInterval();

		mTemperatureMin = mAlarmManager.getTemperatureMin();
		mTemperatureMax = mAlarmManager.getTemperatureMax();
		mTemperatureAlarmInterval = mAlarmManager.getTemperatureAlarmInterval();

		mOxygenMin = mAlarmManager.getOxygenMin();
		mOxygenMax = mAlarmManager.getOxygenMax();
		mOxygenAlarmInterval = mAlarmManager.getOxygenAlarmInterval();

		mConductivityMin = mAlarmManager.getConductivityMin();
		mConductivityMax = mAlarmManager.getConductivityMax();
		mConductivityAlarmInterval = mAlarmManager
				.getConductivityAlarmInterval();

		mWaterLevelMin = mAlarmManager.getWaterLevelMin();
		mWaterLevelMax = mAlarmManager.getWaterLevelMax();
		mWaterLevelAlarmInterval = mAlarmManager.getWaterLevelInterval();

		mPhoneNum = mAlarmManager.getPhoneNum();
		mEmialAddr = mailInfo.getToAddress();
		mPhoneEnable = mAlarmManager.isPhoneEnable();
		mEmailEnable = mailInfo.isEmailEnable();
		mRangEnable = mAlarmManager.isRangEnable();
	}

	private void initAllView() {
		showConductivityView();
		showPhView();
		showOxygenView();
		showTemperatureView();
		showWaterLevelView();
		showAlarmView();

	}

	private void setOnListener() {
		findViewById(R.id.resetcondetivity).setOnClickListener(this);
		findViewById(R.id.intervalcondutivityunit).setOnClickListener(this);
		findViewById(R.id.resetoxygen).setOnClickListener(this);
		findViewById(R.id.intervaloxygenunit).setOnClickListener(this);
		findViewById(R.id.resetph).setOnClickListener(this);
		findViewById(R.id.intervalphunit).setOnClickListener(this);
		findViewById(R.id.resettemperature).setOnClickListener(this);
		findViewById(R.id.intervaltemperatureunit).setOnClickListener(this);
		findViewById(R.id.resetwaterlevel).setOnClickListener(this);
		findViewById(R.id.intervalwaterlevelunit).setOnClickListener(this);

		findViewById(R.id.resetall).setOnClickListener(this);
		findViewById(R.id.iport).setOnClickListener(this);
		findViewById(R.id.export).setOnClickListener(this);
		findViewById(R.id.ok).setOnClickListener(this);
		findViewById(R.id.cancel).setOnClickListener(this);
		findViewById(R.id.mail_setting).setOnClickListener(this);
		findViewById(R.id.rang_select).setOnClickListener(this);
	}

	private void saveAllValue() {
		saveConductivityValue();
		saveOxygenValue();
		savePhValue();
		saveTemperatureValue();
		saveWaterLevelValue();
		saveAlarm();
	}

	private void showAlarmView() {
		((EditText) findViewById(R.id.editTextsms)).setText(mPhoneNum);
		((TextView) findViewById(R.id.textviewemsil)).setText(mEmialAddr);
		((CheckBox) findViewById(R.id.checkBoxsms)).setChecked(mPhoneEnable);
		((CheckBox) findViewById(R.id.checkBoxemail)).setChecked(mEmailEnable);
		((CheckBox) findViewById(R.id.checkBoxerang)).setChecked(mRangEnable);
	}

	private void saveAlarm() {
		mPhoneNum = ((EditText) findViewById(R.id.editTextsms)).getText()
				.toString().trim();
		mPhoneEnable = ((CheckBox) findViewById(R.id.checkBoxsms)).isChecked();
		mEmailEnable = ((CheckBox) findViewById(R.id.checkBoxemail))
				.isChecked();
		mRangEnable = ((CheckBox) findViewById(R.id.checkBoxerang)).isChecked();

		mAlarmManager.setPhoneNum(mPhoneNum);
		mAlarmManager.setPhoneEnable(mPhoneEnable);
		mailInfo.setEmailEnable(mEmailEnable);
		mAlarmManager.setRangEnable(mRangEnable);
	}

	private void showItemView(int id1, float value1, int id2, float value2,
			int id3, int value3, int id4) {
		((TextView) findViewById(id1)).setText(value1 + "");
		((TextView) findViewById(id2)).setText(value2 + "");

		if (value3 > 59 && value3 % 60 == 0) {
			value3 = value3 / 60;
			((TextView) findViewById(id4)).setText(R.string.hour);
		} else {
			((TextView) findViewById(id4)).setText(R.string.minute);
		}

		((TextView) findViewById(id3)).setText(value3 + "");

	}

	private void showConductivityView() {
		int id1 = R.id.mincondutivity;
		int id2 = R.id.maxcondutivity;
		int id3 = R.id.intervalcondutivity;
		int id4 = R.id.intervalcondutivityunit;
		showItemView(id1, mConductivityMin, id2, mConductivityMax, id3,
				mConductivityAlarmInterval, id4);

	}

	private void showConductivityDefault() {

		mConductivityMin = AlarmDefaultValue.MINConductivity;
		mConductivityMax = AlarmDefaultValue.MAXConductivity;
		mConductivityAlarmInterval = AlarmDefaultValue.INTERVALConductivity;
		showConductivityView();

	}

	private void saveConductivityValue() {
		mConductivityMin = Float
				.valueOf(((TextView) findViewById(R.id.mincondutivity))
						.getText().toString().trim());
		mAlarmManager.setConductivityMin(mConductivityMin);
		mConductivityMax = Float
				.valueOf(((TextView) findViewById(R.id.maxcondutivity))
						.getText().toString().trim());
		mAlarmManager.setConductivityMax(mConductivityMax);
		float i = Float
				.valueOf(((TextView) findViewById(R.id.intervalcondutivity))
						.getText().toString().trim());
		if (((TextView) findViewById(R.id.intervalcondutivityunit)).getText()
				.toString().trim().equals(hour)) {
			i = i * 60;
		}
		mConductivityAlarmInterval = (int) i;
		mAlarmManager.setConductivityAlarmInterval(mConductivityAlarmInterval);

	}

	private void showOxygenView() {

		int id1 = R.id.minoxygen;
		int id2 = R.id.maxoxygen;
		int id3 = R.id.intervaloxygen;
		int id4 = R.id.intervaloxygenunit;
		showItemView(id1, mOxygenMin, id2, mOxygenMax, id3,
				mOxygenAlarmInterval, id4);
	}

	private void showOxygenDefault() {
		mOxygenMin = AlarmDefaultValue.MINOxygen;
		mOxygenMax = AlarmDefaultValue.MAXOxygen;
		mOxygenAlarmInterval = AlarmDefaultValue.INTERVALOxygen;
		showOxygenView();
	}

	private void saveOxygenValue() {
		mOxygenMin = Float.valueOf(((TextView) findViewById(R.id.minoxygen))
				.getText().toString().trim());
		mOxygenMax = Float.valueOf(((TextView) findViewById(R.id.maxoxygen))
				.getText().toString().trim());
		mOxygenAlarmInterval = AlarmDefaultValue.INTERVALOxygen;

		mAlarmManager.setOxygenMin(mOxygenMin);
		mAlarmManager.setOxygenMax(mOxygenMax);
		float i = Float.valueOf(((TextView) findViewById(R.id.intervaloxygen))
				.getText().toString().trim());
		String str = ((TextView) findViewById(R.id.intervaloxygenunit))
				.getText().toString().trim();
		if (str.equals(hour)) {
			i = i * 60;
		}
		mOxygenAlarmInterval = (int) i;
		mAlarmManager.setOxygenAlarmInterval(mOxygenAlarmInterval);

	}

	private void showPhView() {
		int id1 = R.id.minph;
		int id2 = R.id.maxph;
		int id3 = R.id.intervalph;
		int id4 = R.id.intervalphunit;
		showItemView(id1, mPhMin, id2, mPhMax, id3, mPhAlarmInterval, id4);
	}

	private void showPhDefault() {
		mPhMin = AlarmDefaultValue.MINPH;
		mPhMax = AlarmDefaultValue.MAXPH;
		mPhAlarmInterval = AlarmDefaultValue.INTERVALPH;
		showPhView();
	}

	private void savePhValue() {
		mPhMin = Float.valueOf(((TextView) findViewById(R.id.minph)).getText()
				.toString().trim());
		mPhMax = Float.valueOf(((TextView) findViewById(R.id.maxph)).getText()
				.toString().trim());

		mAlarmManager.setPhMin(mPhMin);
		mAlarmManager.setPhMax(mPhMax);
		float i = Float.valueOf(((TextView) findViewById(R.id.intervalph))
				.getText().toString().trim());
		if (((TextView) findViewById(R.id.intervalphunit)).getText().toString()
				.trim().equals(hour)) {
			i = i * 60;
		}
		mPhAlarmInterval = (int) i;
		mAlarmManager.setPhAlarmInterval(mPhAlarmInterval);

	}

	private void showTemperatureView() {
		int id1 = R.id.mintemperature;
		int id2 = R.id.maxtemperature;
		int id3 = R.id.intervaltemperature;
		int id4 = R.id.intervaltemperatureunit;
		showItemView(id1, mTemperatureMin, id2, mTemperatureMax, id3,
				mTemperatureAlarmInterval, id4);

	}

	private void showTemperatureDefault() {
		mTemperatureMin = AlarmDefaultValue.MINTEMPERATURE;
		mTemperatureMax = AlarmDefaultValue.MAXTEMPERATURE;
		mTemperatureAlarmInterval = AlarmDefaultValue.INTERVALTEMPERATURE;
		showTemperatureView();
	}

	private void saveTemperatureValue() {
		mTemperatureMin = Float
				.valueOf(((TextView) findViewById(R.id.mintemperature))
						.getText().toString().trim());
		mTemperatureMax = Float
				.valueOf(((TextView) findViewById(R.id.maxtemperature))
						.getText().toString().trim());
		mAlarmManager.setTemperatureMin(mTemperatureMin);
		mAlarmManager.setTemperatureMax(mTemperatureMax);
		float i = Float
				.valueOf(((TextView) findViewById(R.id.intervaltemperature))
						.getText().toString().trim());
		if (((TextView) findViewById(R.id.intervaltemperatureunit)).getText()
				.toString().trim().equals(hour)) {
			i = i * 60;
		}
		mTemperatureAlarmInterval = (int) i;
		mAlarmManager.setTemperatureAlarmInterval(mTemperatureAlarmInterval);

	}

	private void showWaterLevelView() {
		int id1 = R.id.minwaterlevel;
		int id2 = R.id.maxwaterlevel;
		int id3 = R.id.intervalwaterlevel;
		int id4 = R.id.intervalwaterlevelunit;

		showItemView(id1, mWaterLevelMin, id2, mWaterLevelMax, id3,
				mWaterLevelAlarmInterval, id4);
	}

	private void showWaterLevelDefault() {
		mWaterLevelMin = AlarmDefaultValue.MINWATERLEVEL;
		mWaterLevelMax = AlarmDefaultValue.MAXWATERLEVEL;
		mWaterLevelAlarmInterval = AlarmDefaultValue.INTERVALWATERLEVEL;
		showWaterLevelView();
	}

	private void saveWaterLevelValue() {
		mWaterLevelMin = Float
				.valueOf(((TextView) findViewById(R.id.minwaterlevel))
						.getText().toString().trim());
		mWaterLevelMax = Float
				.valueOf(((TextView) findViewById(R.id.maxwaterlevel))
						.getText().toString().trim());

		mAlarmManager.setWaterLevelMin(mWaterLevelMin);
		mAlarmManager.setWaterLevelMax(mWaterLevelMax);
		float i = Float
				.valueOf(((TextView) findViewById(R.id.intervalwaterlevel))
						.getText().toString().trim());
		if (((TextView) findViewById(R.id.intervalwaterlevelunit)).getText()
				.toString().trim().equals(hour)) {
			i = i * 60;
		}
		mWaterLevelAlarmInterval = (int) i;
		mAlarmManager.setWaterLevelAlarmInterval(mWaterLevelAlarmInterval);

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.resetall:
			showConductivityDefault();
			showPhDefault();
			showOxygenDefault();
			showTemperatureDefault();
			showWaterLevelDefault();
			break;
		case R.id.resetcondetivity:
			showConductivityDefault();
			break;
		case R.id.resetoxygen:
			showOxygenDefault();
			break;
		case R.id.resetph:
			showPhDefault();
			break;
		case R.id.resettemperature:
			showTemperatureDefault();
			break;
		case R.id.resetwaterlevel:
			showWaterLevelDefault();
			break;

		case R.id.intervaloxygenunit:
			addPopupMenu(v);
			break;
		case R.id.ok:
			saveAlarm();
			myHandler.sendEmptyMessage(HANDLER_VIEW_DISENABLE);
			myHandler.sendEmptyMessageDelayed(HANDLER_TIMEOUT, TIMEOUT);
			sendData();
			break;
		case R.id.cancel:
			this.finish();
			break;
		case R.id.iport:
			ConfigDOM.readAlarmConfig("aquarium.xml", this);
			break;
		case R.id.export:
			ConfigDOM.writeAlarmConfig("aquarium.xml", this);
			break;
		case R.id.mail_setting:
			Intent intent = new Intent();
			intent.setClass(AlarmSettingActivity.this,
					MailSettingActivity.class);
			startActivity(intent);
			break;
		case R.id.rang_select:
			Intent intentRang = new Intent(
					RingtoneManager.ACTION_RINGTONE_PICKER);
			intentRang.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
					RingtoneManager.TYPE_RINGTONE);
			intentRang.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE,
					getResources().getString(R.string.ringtone));
			startActivityForResult(intentRang, ButtonRingtone);
			break;
		default:
			break;
		}
	}

	class MyHandler extends Handler {

		MyHandler() {
			super();
		}

		MyHandler(Looper l) {
			super(l);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {

			case HANDLER_VIEW_DISENABLE:
				progressDialog = new ProgressDialog(mContext);
				progressDialog.setCancelable(false);
				progressDialog.setMessage(getResources().getString(
						R.string.please_wait));
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progressDialog.show();
				break;
			case HANDLER_VIEW_ENABLE:
				if (progressDialog != null) {
					progressDialog.dismiss();
				}

				// findViewById(R.id.ll_progress).setVisibility(View.GONE);
				// findViewById(R.id.ll_alarm).setVisibility(View.VISIBLE);
				break;
			case HANDLER_TIMEOUT:
				myHandler.sendEmptyMessage(HANDLER_VIEW_ENABLE);
				Toast.makeText(mContext, R.string.alarm_setting_err,
						Toast.LENGTH_SHORT).show();
				break;
			case HANDLER_VERIFY_OK:
				myHandler.removeMessages(HANDLER_TIMEOUT);
				myHandler.sendEmptyMessage(HANDLER_VIEW_ENABLE);
				// saveAllValue();
				finish();
				break;
			case HANDLER_VERIFY_ERR:
				myHandler.sendEmptyMessage(HANDLER_TIMEOUT);
				break;
			case HANDLER_SAVE_CONDUTIVITY:
				saveConductivityValue();
				break;
			case HANDLER_SAVE_OXYGEN:
				saveOxygenValue();
				break;
			case HANDLER_SAVE_PH:
				savePhValue();
				break;
			case HANDLER_SAVE_TEMPERATURE:
				saveTemperatureValue();
				break;
			case HANDLER_SAVE_WATERLEVEL:
				saveWaterLevelValue();
				break;

			default:
				break;
			}

		}
	}

	@SuppressLint("NewApi")
	public void addPopupMenu(final View v) {
		PopupMenu popup = new PopupMenu(this, v);
		popup.getMenuInflater().inflate(R.menu.minutehour, popup.getMenu());
		popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				CharSequence str = item.getTitle();
				((Button) v).setText(str);
				return true;
			}

		});

		popup.show();
	}

	private void sendData() {
		getViewValue();
		sendFlag = 0;
		receiveFlag = 0;

		byte[] conductivityBytes = null;
		byte[] oxygenBytes = null;
		byte[] phBytes = null;
		byte[] temperatureBytes = null;
		byte[] waterLevelBytes = null;

		if (mincondutivity >= maxcondutivity
				|| mincondutivity < mSettingConductivityMin
				|| maxcondutivity > mSettingConductivityMax) {
			Log.d(TAG, "1");
			myHandler.sendEmptyMessage(HANDLER_VIEW_ENABLE);
			Toast.makeText(mContext, R.string.data_error, Toast.LENGTH_LONG)
					.show();
			myHandler.removeMessages(HANDLER_TIMEOUT);
			return;
		}
		if (mincondutivity != mConductivityMin
				|| maxcondutivity != mConductivityMax) {
			sendFlag = sendFlag | FLAG_CONDUCTIVITY;
			float i = Float
					.valueOf(((TextView) findViewById(R.id.intervalcondutivity))
							.getText().toString().trim());
			if (((TextView) findViewById(R.id.intervalcondutivityunit))
					.getText().toString().trim().equals(hour)) {
				i = i * 60;
			}
			mConductivityAlarmInterval = (int) i;
			conductivityBytes = BTCommand.getSetConductivityRangeCommand(
					mincondutivity, maxcondutivity, mConductivityAlarmInterval);
			// float[] mValue = mDataInterpreter
			// .unpackConductivityAlarmData(DataInterpreter
			// .unpack(conductivityBytes).data);
			// ((TextView) findViewById(R.id.mincondutivity)).setText(mValue[0]
			// + "");
			// ((TextView) findViewById(R.id.maxcondutivity)).setText(mValue[1]
			// + "");
		}

		if (minoxygen >= maxoxygen || minoxygen < mSettingOxygenMin
				|| maxoxygen > mSettingOxygenMax) {
			myHandler.sendEmptyMessage(HANDLER_VIEW_ENABLE);
			Toast.makeText(mContext, R.string.data_error, Toast.LENGTH_LONG)
					.show();
			myHandler.removeMessages(HANDLER_TIMEOUT);
			return;
		}
		if (minoxygen != mOxygenMin || maxoxygen != mOxygenMax) {
			sendFlag = sendFlag | FLAG_OXYGEN;
			float i = Float
					.valueOf(((TextView) findViewById(R.id.intervaloxygen))
							.getText().toString().trim());
			String str = ((TextView) findViewById(R.id.intervaloxygenunit))
					.getText().toString().trim();
			if (str.equals(hour)) {
				i = i * 60;
			}
			mOxygenAlarmInterval = (int) i;
			oxygenBytes = BTCommand.getSetOxygenRangeCommand(minoxygen,
					maxoxygen, mOxygenAlarmInterval);
			// float[] mValue = mDataInterpreter
			// .unpackOxygenAlarmData(DataInterpreter.unpack(oxygenBytes).data);
			// ((TextView) findViewById(R.id.minoxygen)).setText(mValue[0] +
			// "");
			// ((TextView) findViewById(R.id.maxoxygen)).setText(mValue[1] +
			// "");
		}

		if (minph >= maxph || minph < mSettingPhMin || maxph > mSettingPhMax) {
			Log.d(TAG, "13");
			myHandler.sendEmptyMessage(HANDLER_VIEW_ENABLE);
			Toast.makeText(mContext, R.string.data_error, Toast.LENGTH_LONG)
					.show();
			myHandler.removeMessages(HANDLER_TIMEOUT);
			return;
		}
		if (minph != mPhMin || maxph != mPhMax) {
			sendFlag = sendFlag | FLAG_PH;
			float i = Float.valueOf(((TextView) findViewById(R.id.intervalph))
					.getText().toString().trim());
			if (((TextView) findViewById(R.id.intervalphunit)).getText()
					.toString().trim().equals(hour)) {
				i = i * 60;
			}
			mPhAlarmInterval = (int) i;
			phBytes = BTCommand.getSetPhRangeCommand(minph, maxph,
					mPhAlarmInterval);
			// float[] mValue =
			// mDataInterpreter.unpackPhAlarmData(DataInterpreter
			// .unpack(phBytes).data);
			// ((TextView) findViewById(R.id.minph)).setText(mValue[0] + "");
			// ((TextView) findViewById(R.id.maxph)).setText(mValue[1] + "");
		}

		mintemperature = Float
				.valueOf(((TextView) findViewById(R.id.mintemperature))
						.getText().toString().trim());
		maxtemperature = Float
				.valueOf(((TextView) findViewById(R.id.maxtemperature))
						.getText().toString().trim());
		if (mintemperature >= maxtemperature
				|| mintemperature < mSettingTemperatureMin
				|| maxtemperature > mSettingTemperatureMax) {
			Log.d(TAG, "14");
			myHandler.sendEmptyMessage(HANDLER_VIEW_ENABLE);
			Toast.makeText(mContext, R.string.data_error, Toast.LENGTH_LONG)
					.show();
			myHandler.removeMessages(HANDLER_TIMEOUT);
			return;
		}
		if (mintemperature != mTemperatureMin
				|| maxtemperature != mTemperatureMax) {
			sendFlag = sendFlag | FLAG_TEMPERATURE;
			float i = Float
					.valueOf(((TextView) findViewById(R.id.intervaltemperature))
							.getText().toString().trim());
			if (((TextView) findViewById(R.id.intervaltemperatureunit))
					.getText().toString().trim().equals(hour)) {
				i = i * 60;
			}
			mTemperatureAlarmInterval = (int) i;
			temperatureBytes = BTCommand.getSetTemperatureRangeCommand(
					mintemperature, maxtemperature, mTemperatureAlarmInterval);
			// float[] mValue = mDataInterpreter
			// .unpackTemperatureAlarmData(DataInterpreter
			// .unpack(temperatureBytes).data);
			// ((TextView) findViewById(R.id.mintemperature)).setText(mValue[0]
			// + "");
			// ((TextView) findViewById(R.id.maxtemperature)).setText(mValue[1]
			// + "");
		}

		if (minwaterlevel >= maxwaterlevel
				|| minwaterlevel < mSettingWaterLevelMin
				|| maxwaterlevel > mSettingWaterLevelMax) {
			Log.d(TAG, "15");
			myHandler.sendEmptyMessage(HANDLER_VIEW_ENABLE);
			Toast.makeText(mContext, R.string.data_error, Toast.LENGTH_LONG)
					.show();
			myHandler.removeMessages(HANDLER_TIMEOUT);
			return;
		}
		if (minwaterlevel != mWaterLevelMin || maxwaterlevel != mWaterLevelMax) {
			sendFlag = sendFlag | FLAG_WATERLEVEL;
			float i = Float
					.valueOf(((TextView) findViewById(R.id.intervalwaterlevel))
							.getText().toString().trim());
			if (((TextView) findViewById(R.id.intervalwaterlevelunit))
					.getText().toString().trim().equals(hour)) {
				i = i * 60;
			}
			mWaterLevelAlarmInterval = (int) i;
			waterLevelBytes = BTCommand.getSetWaterLevelRangeCommand(
					minwaterlevel, maxwaterlevel, mWaterLevelAlarmInterval);
			// float[] mValue = mDataInterpreter
			// .unpackWaterLevelAlarmData(DataInterpreter
			// .unpack(waterLevelBytes).data);
			// ((TextView) findViewById(R.id.minwaterlevel)).setText(mValue[0]
			// + "");
			// ((TextView) findViewById(R.id.maxwaterlevel)).setText(mValue[1]
			// + "");
		}

		if (phBytes != null) {
			Log.d(TAG, "send phBytes ");
			for (int i = 0; i < phBytes.length; i++) {
				Log.d(TAG, "data:" + Integer.toHexString(phBytes[i] & 0xFF));
			}
			mBtManager.sendData(DataInterpreter.unpack(phBytes));
			// float[] mValue = mDataInterpreter
			// .unpackPhAlarmData(DataInterpreter.unpack(phBytes).data);
			// Log.d(TAG, "mValue[0]" + mValue[0] + "mValue[1]"
			// + mValue[1] + minph + " " + maxph);
			// mBtManager.sendHpAlarmValue(minph, maxph);
		}

		if (oxygenBytes != null) {
			Log.d(TAG, "send oxygenBytes ");
			for (int i = 0; i < oxygenBytes.length; i++) {
				Log.d(TAG, "data:" + Integer.toHexString(oxygenBytes[i] & 0xFF));
			}
			mBtManager.sendData(DataInterpreter.unpack(oxygenBytes));
			// mBtManager.sendOxygenAlarmValue(minoxygen, maxoxygen);
		}

		if (conductivityBytes != null) {
			Log.d(TAG, "send conductivityBytes ");
			for (int i = 0; i < conductivityBytes.length; i++) {
				Log.d(TAG,
						"data:"
								+ Integer
										.toHexString(conductivityBytes[i] & 0xFF));
			}
			mBtManager.sendData(DataInterpreter.unpack(conductivityBytes));
			// mBtManager.sendConductivityAlarmValue(mincondutivity,
			// maxcondutivity);
		}

		if (temperatureBytes != null) {
			Log.d(TAG, "send temperatureBytes ");
			for (int i = 0; i < temperatureBytes.length; i++) {
				Log.d(TAG,
						"data:"
								+ Integer
										.toHexString(temperatureBytes[i] & 0xFF));
			}
			mBtManager.sendData(DataInterpreter.unpack(temperatureBytes));
			// mBtManager
			// .sendTemperatureAlarmValue(mintemperature, maxtemperature);
		}

		if (waterLevelBytes != null) {
			Log.d(TAG, "send waterLevelBytes ");
			for (int i = 0; i < waterLevelBytes.length; i++) {
				Log.d(TAG,
						"data:"
								+ Integer
										.toHexString(waterLevelBytes[i] & 0xFF));
			}
			mBtManager.sendData(DataInterpreter.unpack(waterLevelBytes));
			// mBtManager.sendWaterLevelAlarmValue(minwaterlevel,
			// maxwaterlevel);
		}

		Log.d(TAG, "sendFlag" + sendFlag + "receiveFlag" + receiveFlag);
		if (sendFlag == 0) {
			myHandler.sendEmptyMessage(HANDLER_VERIFY_OK);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// initAllView();
		initValue();
		((TextView) findViewById(R.id.textviewemsil)).setText(mEmialAddr);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mBtManager.deleteObserver(this);
		mAlarmManager.deleteObserver(this);

	}

	@Override
	public void update(Observable observable, Object data) {

		if (observable instanceof BTManager) {
			// Log.d(TAG, "BTManager update");
			final DataStruct receivedData = (DataStruct) data;
			if (receivedData.prefix == 0x5a && receivedData.id == 0x01
					&& receivedData.length == 1
					&& receivedData.data.length == 1) {
				switch (receivedData.code) {
				case BTCommand.CODE_SET_HP_VALUE:
					if (receivedData.data[0] == 0x00) {
						receiveFlag = receiveFlag | FLAG_PH;
						Log.d(TAG, "ph verify ok");
						myHandler.sendEmptyMessage(HANDLER_SAVE_PH);
					}
					break;
				case BTCommand.CODE_SET_TEMPERATURE_VALUE:

					if (receivedData.data[0] == 0x00) {
						receiveFlag = receiveFlag | FLAG_TEMPERATURE;
						Log.d(TAG, "FLAG_TEMPERATURE verify ok");
						myHandler.sendEmptyMessage(HANDLER_SAVE_TEMPERATURE);
					}
					break;
				case BTCommand.CODE_SET_OXYGEN_VALUE:
					if (receivedData.data[0] == 0x00) {
						receiveFlag = receiveFlag | FLAG_OXYGEN;
						Log.d(TAG, "FLAG_OXYGEN verify ok");
						myHandler.sendEmptyMessage(HANDLER_SAVE_OXYGEN);
					}
					break;
				case BTCommand.CODE_SET_CONDUCTIVITY_VALUE:
					if (receivedData.data[0] == 0x00) {
						receiveFlag = receiveFlag | FLAG_CONDUCTIVITY;
						Log.d(TAG, "FLAG_CONDUCTIVITY verify ok");
						myHandler.sendEmptyMessage(HANDLER_SAVE_CONDUTIVITY);
					}
					break;
				case BTCommand.CODE_SET_WATER_LEVEL_VALUE:
					if (receivedData.data[0] == 0x00) {
						receiveFlag = receiveFlag | FLAG_WATERLEVEL;
						Log.d(TAG, "FLAG_WATERLEVEL verify ok");
						myHandler.sendEmptyMessage(HANDLER_SAVE_WATERLEVEL);
					}
					break;
				default:
					return;
				}
				Log.d(TAG, "receiveFlag" + receiveFlag);
				if (receiveFlag != 0 && receiveFlag == sendFlag) {
					myHandler.sendEmptyMessage(HANDLER_VERIFY_OK);
				}
			}

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case ButtonRingtone:
			try {
				// 得到我们选择的铃声
				Uri pickedUri = data
						.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
				// 将我们选择的铃声设置成为默认
				if (pickedUri != null) {
					mAlarmManager.setRangUri(pickedUri);
				}
			} catch (Exception e) {
			}
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (myHandler != null) {
			myHandler.removeMessages(HANDLER_TIMEOUT);
			myHandler.sendEmptyMessage(HANDLER_VIEW_ENABLE);
		}
		if (progressDialog != null) {
			progressDialog.dismiss();
		}

	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (isValeChange()) {
				requestSaveSettings();
				return true;
			} else {
				finish();
				return false;
			}
		}
		return super.onKeyUp(keyCode, event);
	}

	private void requestSaveSettings() {
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		LayoutInflater inflater = this.getLayoutInflater();
		final View view = inflater.inflate(R.layout.dialog_controller_setting,
				null);

		// builder.setView(view)
		builder.setMessage(getString(R.string.save_alarm_setting))
				.setPositiveButton(R.string.save,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.dismiss();
								myHandler
										.sendEmptyMessage(HANDLER_VIEW_DISENABLE);
								myHandler.sendEmptyMessageDelayed(
										HANDLER_TIMEOUT, TIMEOUT);
								sendData();
								// finish();
							}
						})
				.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								finish();
							}
						}).create().show();
	}

	boolean isValeChange() {
		getViewValue();
		boolean tmp = false;
		if (minwaterlevel != mWaterLevelMin
				|| maxwaterlevel != mWaterLevelMax
				|| mintemperature != mTemperatureMin
				|| maxtemperature != mTemperatureMax
				|| minph != mPhMin
				|| maxph != mPhMax
				|| mincondutivity != mConductivityMin
				|| maxcondutivity != mConductivityMax
				|| minoxygen != mOxygenMin
				|| maxoxygen != mOxygenMax
				|| mPhoneNum != ((EditText) findViewById(R.id.editTextsms))
						.getText().toString().trim()
				|| mPhoneEnable != ((CheckBox) findViewById(R.id.checkBoxsms))
						.isChecked()
				|| mEmailEnable != ((CheckBox) findViewById(R.id.checkBoxemail))
						.isChecked()
				|| mRangEnable != ((CheckBox) findViewById(R.id.checkBoxerang))
						.isChecked()) {

			tmp = true;
		}
		return tmp;
	}

	void getViewValue() {
		mincondutivity = Float
				.valueOf(((TextView) findViewById(R.id.mincondutivity))
						.getText().toString().trim());
		maxcondutivity = Float
				.valueOf(((TextView) findViewById(R.id.maxcondutivity))
						.getText().toString().trim());
		minoxygen = Float.valueOf(((TextView) findViewById(R.id.minoxygen))
				.getText().toString().trim());
		maxoxygen = Float.valueOf(((TextView) findViewById(R.id.maxoxygen))
				.getText().toString().trim());
		minph = Float.valueOf(((TextView) findViewById(R.id.minph)).getText()
				.toString().trim());
		maxph = Float.valueOf(((TextView) findViewById(R.id.maxph)).getText()
				.toString().trim());
		mintemperature = Float
				.valueOf(((TextView) findViewById(R.id.mintemperature))
						.getText().toString().trim());
		maxtemperature = Float
				.valueOf(((TextView) findViewById(R.id.maxtemperature))
						.getText().toString().trim());
		minwaterlevel = Float
				.valueOf(((TextView) findViewById(R.id.minwaterlevel))
						.getText().toString().trim());
		maxwaterlevel = Float
				.valueOf(((TextView) findViewById(R.id.maxwaterlevel))
						.getText().toString().trim());
	}
}
